<template>
  <div class="planning-drawer-container" :class="{ 'drawer-hidden': !sidebarOpen }">
    <div class="planning-drawer" :class="{ 'drawer-open': isOpen }">
      <div class="drawer-content">
        <div class="drawer-header">
          <h3 class="planning-title">行程规划</h3>
        </div>

        <div class="drawer-body">
          <draggable-spot-list 
            ref="draggableListRef"
            v-model:spots="spots"
            :map-ref="props.mapRef"
           :spot-analysis-results="spotAnalysisResults"
           @transport-click="handleTransportClick" 
            @delete="handleSpotDelete" 
           @show-tooltip="handleTooltipShow"
           @show-analysis="$emit('show-analysis', $event)"
           @clear-markers="handleclearMarkers"
           @add-marker="$emit('add-marker', $event)"
           />

        </div>

        <div class="drawer-footer">
          <el-button @click="clearSpots">清空</el-button>
          <el-button type="primary" @click="showAiDialog" :loading="gptStore.loading">
            获取AI建议
          </el-button>
        </div>

        <div class="drawer-handle" @click="$emit('toggle')">
          <el-icon :size="20" class="handle-icon">
            <component :is="isOpen ? ArrowLeft : ArrowRight" />
          </el-icon>
        </div>
      </div>
    </div>
    <AISuggestionDialog v-model:visible="dialogVisible" :spot-ids="spots.map(spot => spot.attractionId)" :spots="spots"
      @submit="handleAiSubmit" ref="dialogRef" />
    </div>
    
</template>

<script setup lang="ts">
import { ref,onUnmounted,watch} from 'vue'
import { ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import DraggableSpotList from './DraggableSpotList.vue'
import { ElMessage } from 'element-plus';
import { useGptStore } from '@/stores/GptStore'
import AISuggestionDialog from '../ai/AIInput/AISuggestionDialog.vue'
import { spotAnalysis } from '@/api/Gpt'

interface Props {
  isOpen: boolean
  sidebarOpen: boolean
  mapRef: Object
}

interface Spot {
  // 基本标识
  attractionId: number
  regionId: number

  // 基本信息
  name: string
  description: string
  address: string
  image: string

  // 位置信息
  latitude: number
  longitude: number

  // 详细信息
  priceRange: string
  openingHours: string
  likeCount: number
  commentCount: number
  attractionRating: number
  recommendedVisitTime: string
  recommendedVisitSeason: string
  selectCount: number

  // 规划相关
  duration?: number
  aiSuggestion?: string
  distance?: number
}
// 定义响应类型
interface SpotDetail {
  name: string
  description: string
  detailed_analysis: string
  visiting_tips: string
  budget_estimation: string
  recommended_duration: string
}

interface Analysis {
  summary: string
  travel_tips: string
  budget_analysis: string
}

interface ApiResponse {
  status: string
  message: string
  data: {
    spot_details: SpotDetail[]
    analysis: Analysis
  }
}

//细节GPT
interface SpotAnalysisDetail {
  spotId: number
  name: string
  analysis: {
    detailed_analysis: string
    visiting_tips: string
    budget_estimation: string
    recommended_duration: string
  }
}
const props = defineProps<Props>()
const emit = defineEmits(['toggle', 'add-marker', 'remove-marker', 'show-analysis'])
const spots = ref<Spot[]>([])
const dialogVisible = ref(false)
const dialogRef = ref<InstanceType<typeof AISuggestionDialog>>()
const gptStore = useGptStore()
const draggableListRef = ref<InstanceType<typeof DraggableSpotList>>()
const localIsOpen = ref(props.isOpen)

const spotAnalysisResults = ref<SpotAnalysisDetail[]>([])

// 添加景点
const addSpot = (newSpot: any) => {
  const isDuplicate = spots.value.some(spot => spot.attractionId === newSpot.attractionId)

  if (isDuplicate) {
    ElMessage.warning('该景点已在行程中')
    return
  }

  spots.value = [...spots.value, {
    attractionId: newSpot.attractionId,
    regionId: newSpot.regionId,
    name: newSpot.name,
    description: newSpot.description,
    address: newSpot.address,
    image: newSpot.image,
    latitude: newSpot.latitude,
    longitude: newSpot.longitude,
    priceRange: newSpot.priceRange,
    openingHours: newSpot.openingHours,
    likeCount: newSpot.likeCount,
    commentCount: newSpot.commentCount,
    attractionRating: newSpot.attractionRating,
    recommendedVisitTime: newSpot.recommendedVisitTime,
    recommendedVisitSeason: newSpot.recommendedVisitSeason,
    selectCount: newSpot.selectCount,
    duration: newSpot.recommendedVisitTime ? parseInt(newSpot.recommendedVisitTime) : 120,
    aiSuggestion: '暂无建议',
    distance: newSpot.distance
  }]
  emit('add-marker', newSpot)
  ElMessage.success('已添加到行程')
}

// 清空景点
const clearSpots = () => {
  spots.value.forEach(spot => {
    emit('remove-marker', spot.attractionId)
  })
  spots.value = []
}

// 显示AI建议对话框
const showAiDialog = () => {
  if (!spots.value.length) {
    ElMessage.warning('请先添加景点')
    return
  }
  dialogVisible.value = true
}

// 切换规划抽屉
const togglePlanningDrawer = () => {
  localIsOpen.value = !localIsOpen.value
  emit('toggle') // 保持现有的emit逻辑
}

// 处理Tooltip显示
const handleTooltipShow = (tooltipData: {
  spotId: number,
  content: string,
  position: number
}) => {
  console.log('Tooltip显示:', tooltipData)
  // 这里可以进行其他处理，比如更新状态或触发其他动作
}

// 处理清除标记
const handleclearMarkers = (spotIds) => {
  spotIds.forEach(attractionId => {
    emit('remove-marker', attractionId)
  })
}

// 修改 handleAiSubmit 函数
const handleAiSubmit = async (data: any) => {
  try {
    gptStore.loading = true
    console.log('发送请求数据:', data)

    // 获取axios响应并处理
    const axiosResponse = await spotAnalysis(data)
    // 先转换为 unknown，再断言为 ApiResponse
    const response = axiosResponse as unknown as ApiResponse

    if (response?.status === 'success') {
      // 更新景点详细信息
      spotAnalysisResults.value = response.data.spot_details.map(detail => {
        const spot = spots.value.find(s => s.name.includes(detail.name))
        return {
          spotId: spot?.attractionId || 0,
          name: detail.name,
          analysis: {
            detailed_analysis: detail.detailed_analysis,
            visiting_tips: detail.visiting_tips,
            budget_estimation: detail.budget_estimation,
            recommended_duration: detail.recommended_duration
          }
        }
      })
      console.log('更新后的spotAnalysisResults:', spotAnalysisResults.value)
      // 保存分析结果
      await gptStore.addAnalysis(response)
      
      // 显示结果对话框
      dialogRef.value?.showResult(response)
      dialogVisible.value = false
    } else {
      throw new Error(response?.message || '响应数据格式不正确')
    }
  } catch (error) {
    console.error('AI分析请求失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '获取AI建议失败，请稍后重试')
  } finally {
    gptStore.loading = false
  }
}

const handleTransportClick = (index: number) => {
  // TODO: 处理交通方式点击事件
}
// 添加删除处理方法
const handleSpotDelete = (attractionId: number) => {
  emit('remove-marker', attractionId)
}

watch(() => props.isOpen, (newValue) => {
  localIsOpen.value = newValue
})

// 更新defineExpose
defineExpose({
  addSpot,
  clearSpots,
  draggableListRef,
  togglePlanningDrawer,
  isOpen: localIsOpen  // 暴露本地状态
})
onUnmounted(() => {
  gptStore.loading = false
  spots.value = []
})
</script>

<style scoped>
.planning-drawer-container {
  position: absolute;
  top: 0;
  left: 400px;
  height: 100%;
  pointer-events: none;
  z-index: 190;
}

.planning-drawer {
  position: relative;
  width: 300px;
  height: 100%;
  transform: translateX(-100%);
  transition: transform 0.3s ease;
  pointer-events: auto;
}

.drawer-content {
  height: 100%;
  background: white;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #eee;
  border-top-right-radius: 12px;
  border-bottom-right-radius: 12px;
  overflow: hidden;
}

.planning-title {
  text-align: right;
  margin: 12px 0 4px;
  font-size: 18px;
  color: #333;
  font-weight: 600;
  padding-bottom: 8px;
}


.drawer-header {
  padding: 8px 20px 12px;
  border-bottom: 1px solid #eee;
}

.drawer-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.drawer-handle {
  position: absolute;
  top: 50%;
  right: -30px;
  transform: translateY(-50%);
  width: 30px;
  height: 60px;
  background: white;
  border-radius: 0 4px 4px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  pointer-events: auto;
  z-index: 191;
  /* 稍高于drawer本身，确保可以点击 */
}

.drawer-footer {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
}

.drawer-open {
  transform: translateX(0);
}

.drawer-hidden {
  display: none;
}

.handle-icon {
  color: #606266;
}
</style>